package com.example.tilitili.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.tilitili.exception.GlobalException;
import com.example.tilitili.mapper.UserMapper;
import com.example.tilitili.pojo.User;
import com.example.tilitili.service.IUserService;
import com.example.tilitili.utils.CookieUtil;
import com.example.tilitili.utils.MD5Util;
import com.example.tilitili.utils.UUIDUtil;
import com.example.tilitili.utils.ValidatorUtil;
import com.example.tilitili.vo.LoginVo;
import com.example.tilitili.vo.RegisterVo;
import com.example.tilitili.vo.RespBean;
import com.example.tilitili.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 * @author chenyu
 * @since 2022-01-11
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    //@Autowired(required = false)
    @Resource
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public RespBean doLogin(LoginVo loginVo,  HttpServletRequest request,HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        //根据手机号获取用户
        User user = userMapper.selectById(mobile);
        if (null==user){
            throw new GlobalException(RespBeanEnum.LOGINVO_ERROR);
        }
        //校验密码
        if (!MD5Util.formPassToDBPass(password,user.getSalt()).equals(user.getPassword())){
            throw new GlobalException(RespBeanEnum.LOGINVO_ERROR);
        }
        //生成cookie
        String ticket = UUIDUtil.uuid();
        //equest.getSession().setAttribute(ticket,user);
        //将用户信息存入redis
        redisTemplate.opsForValue().set("user:"+ticket,user);
        CookieUtil.setCookie(request,response,"userTicket",ticket);
        return RespBean.success(ticket);
    }

    @Override
    public User getByUserTicket(String userTicket,HttpServletRequest request,HttpServletResponse response) {
        if(StringUtils.isEmpty(userTicket))
        {
            return null;
        }
        User user = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        if(user!=null)
        {
            CookieUtil.setCookie(request,response,"userTicket",userTicket);
        }
        return user;
    }

    /**
     * 注册
     * @param registerVo
     * @return
     */
    @Override
    @Transactional
    public RespBean doregister(RegisterVo registerVo, HttpServletRequest request,HttpServletResponse response) {

        String mobile=registerVo.getMobile();
        String password=registerVo.getPassword();
        String password2= registerVo.getPassword2();
        String nickname= registerVo.getNickname();
        String address=registerVo.getAddress();

        //log.info("{}",mobile);
        /**
         * 判断手机号码填入是否正确
         */
        if(StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)){
            return RespBean.error(RespBeanEnum.LOGINVO_ERROR);
        }
        if (!ValidatorUtil.isMobile(mobile)){
            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
        }

        User user=new User();
        user=userMapper.selectById(mobile);
        //根据手机号查看用户是否存在
        if(user!=null){
            return RespBean.error(RespBeanEnum.MOBILE_EXIST);
        }
        //判断两次输入密码是否一致
        if(!password.equals(password2)){
            return RespBean.error(RespBeanEnum.PASSWORD_ERROR);
        }
        user=register(registerVo);
        return RespBean.success();
    }

    @Override
    public User register(RegisterVo registerVo){
        User user=new User();
        user.setNickname(registerVo.getNickname());
        user.setId(Long.parseLong(registerVo.getMobile()));
        user.setSalt("1abv4k76e");
        user.setPassword(MD5Util.inputPassToDbPass(registerVo.getPassword(), user.getSalt()));
        user.setAddress(registerVo.getAddress());
        userMapper.insert(user);
        return user;
    }

    /**
     * 更新密码
     *
     * @param userTicket
     * @param id
     * @param password
     * @return
     */
    @Override
    public RespBean updatePassword(String userTicket, Long id, String password) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new GlobalException(RespBeanEnum.MOBILE_NOT_EXIST);
        }
        user.setPassword(MD5Util.inputPassToDbPass(password, user.getSalt()));
        int result = userMapper.updateById(user);
        if (1 == result) {
            //删除Redis
            redisTemplate.delete("user:" + userTicket);
            return RespBean.success();
        }
        return RespBean.error(RespBeanEnum.PASSWORD_UPDATE_FAIL);
    }
}
